
#import "RNVideocompress.h"
#import <AVFoundation/AVFoundation.h>
#import <UIKit/UIKit.h>
@implementation RNVideocompress

- (dispatch_queue_t)methodQueue
{
    return dispatch_get_main_queue();
}
RCT_EXPORT_MODULE()
RCT_REMAP_METHOD(zipVideo,
                 path:(NSString*)path
                 resolve:(RCTPromiseResolveBlock)resolve
                 reject:(RCTPromiseRejectBlock)reject){

    NSString *pathDocuments = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    NSString *videoPath = [NSString stringWithFormat:@"%@/%@.mp4", pathDocuments,[[NSUUID UUID] UUIDString]];
    NSURL* originFilePath = [NSURL fileURLWithPath:path];

    //创建一个由URL标识的代表任何资源的assert对象
    AVURLAsset *asset =  [AVURLAsset URLAssetWithURL:originFilePath options:nil];
    //转码配置   建议选择AVAssetExportPresetMediumQuality
    AVAssetExportSession *exportSession= [[AVAssetExportSession alloc] initWithAsset:asset presetName:AVAssetExportPresetMediumQuality];
    exportSession.shouldOptimizeForNetworkUse = YES;
    exportSession.outputURL = [NSURL fileURLWithPath:videoPath];

    //AVFileTypeMPEG4 文件输出类型，可以更改，是枚举类型，官方有提供，更改该值也可以改变视频的压缩比例
    exportSession.outputFileType = AVFileTypeMPEG4;

    [exportSession exportAsynchronouslyWithCompletionHandler:^{
        AVAssetExportSessionStatus exportStatus = exportSession.status;
        switch (exportStatus)
        {
            case AVAssetExportSessionStatusFailed:
            {
                NSError *exportError = exportSession.error;
                NSLog (@"转码失败 AVAssetExportSessionStatusFailed: %@", exportError);
                reject(@"-10",@"转码失败",nil);
                break;
            }
            case AVAssetExportSessionStatusCompleted:
            {
                NSLog(@"视频转码成功");
                resolve(videoPath);
                break;

            }
            default:{
                 reject(@"-10",@"转码失败",nil);
                 break;
            }
        }
    }];
}

@end

